package org.hq.controller;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.hq.pojo.LoginUser;
import org.hq.pojo.WebUser;
import org.hq.service.TokenService;
import org.hq.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.HashMap;
import java.util.Map;


@Controller
public class Login {
    @Autowired
    private AuthenticationManager am;
    @Autowired
    private TokenService ts;
    @GetMapping(value ="/myuserss")
    public String myuserss(){
        System.out.println("myuserss");
        return "myuserss";
    }

    /**
     * 用户登录页面
     * @return
     */
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @PostMapping("/myuser")
    public R<String> logintojson(String username, String password, HttpServletResponse response) {
        System.out.println("登录系统用户 "+username);
        try {
            // 封装登录系统用户
            UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(username, password);
            //认证处理
            Authentication authenticate = am.authenticate(upa);
            //判断是否认证成功
            //将认证用户保存到上下文去
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            // 获取系统登录用户保存到redis
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            WebUser user = loginUser.getUser();
            // long time= 5L * TimeUnit.MINUTES;

            //保存 token
            String token= ts.saveToken(user,600 );
            user.setToken(token);
            Map map =new HashMap() ;
            map.put("code",0);
            map.put("message","登录成功");
            map.put("data",user);

            //把对象转换为字符串
            String json = JSON.toJSONString(map);
            //设置返回类型
           // response.setContentType("application/json;charset=utf-8");
            //返回结果
            //response.getWriter().println(json);

            return R.ok(json);
        } catch (Exception e) {

        }

        return R.no();
    }


}
